package com.yenlien.traceyun.control.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.dao.RepaymentDao;
import com.yenlien.traceyun.control.entity.Repayment;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import com.yenlien.traceyun.control.service.LoanInfoService;
import com.yenlien.traceyun.control.service.RepaymentService;
import com.yenlien.traceyun.webase.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 还款计划表
 */
@RestController
@RequestMapping("/repayment")
public class RepaymentController extends BaseController {

    @Autowired
    private RepaymentService repaymentService;

    @Autowired
    private RepaymentDao repaymentDao;


    /**
     * 列表分页查询
     */
    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody Repayment repayment) {
        if (StringUtils.isEmpty(repayment.getBankInfoId())) {
            String companyId = UserAuthUtil.getLoginUser().getCompanyId();
            repayment.setCompanyId(companyId);
        }
        return buildPage(repaymentService.findByList(repayment));
    }

    /**
     * 根据ID查询单个详情
     */
    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable("id") String id) {
        return repaymentService.findById(id);
    }


    /**
     * 合作社用户发起还款请求，银行端管理员审核还款信息
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(@RequestBody Repayment repayment) {
        Repayment pay = repaymentDao.findById(repayment.getId()).get();     //获取当前期数数据
        int stageNum = pay.getLoanPeriod() - pay.getSurplusNum();       //当前期数
        Integer bySumNum = repaymentDao.findBySumNum(repayment.getLoanId());        //统计的已经还款的期数

        BigDecimal number = new BigDecimal(stageNum).subtract(new BigDecimal(bySumNum));
        int number2 = number.compareTo(new BigDecimal(1));
        if (number2 != 0) {
            return fail("只能按期数数序还款");
        }
        Object num = repaymentService.save(repayment);
        if (num.equals(0)) {
            return fail("操作失败");
        }
        return success("操作成功");
    }

    /**
     * ,审核贷款， 生成还款计划表
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public Object payRepayment(@RequestBody Repayment repayment) {
        return repaymentService.pay(repayment);
    }

}
